package pos.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import Clases.domain.Causa;
import Clases.domain.Manifestacion;
import Clases.domain.Zona;

public class JDBCZonaDAO implements IZonaDAO {

	IContenedorDAO contenedor;

	IManifestacionDAO manifestacion;

	ICausaDAO causa;

	IUsuarioDAO usuario;

	public JDBCZonaDAO() {

		contenedor = new JDBCContenedorDAO();
		manifestacion = new JDBCManifestacionDAO();
		causa = new JDBCCausaDAO();
		usuario = new JDBCUsuarioDAO();
	}

	public List selectCalles(Connection conn, Integer zonaOID) {

		PreparedStatement stmt = null;
		List searchResults = new LinkedList();
		ResultSet result = null;
		String nombre = null;

		try {

			String sql = "SELECT nombre FROM Calles C WHERE C.zonaOID ='"
					+ zonaOID + "'";
			stmt = conn.prepareStatement(sql);

			result = stmt.executeQuery();

			while (result.next()) {
				searchResults.add(result.getString("nombre"));
			}

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {

			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException e) {
			}

		}
		return searchResults;

	}

	public List selectZonasBarrio(Connection conn, Integer barrioOID) {

		String sql = "SELECT * FROM Zona WHERE (barrioOID LIKE '" + barrioOID
				+ "')";

		PreparedStatement stmt = null;
		ResultSet result = null;
		List zonas = new LinkedList();

		try {
			stmt = conn.prepareStatement(sql);
			result = stmt.executeQuery();
			while (result.next()) {
				List c = new LinkedList();
				Zona z = new Zona();
				z.setNombre(result.getString("nombre"));
				Integer zoid = result.getInt("zonaOID");
				c.addAll(selectCalles(conn, zoid));
				z.setCalles(c);
				z.setCausas(causa.selectAllCausasZona(conn, zoid));
				z.setContenedores(contenedor.selectContenedorZona(conn, zoid));
				z.setManif(manifestacion.selectManifestacionZona(conn, zoid));
				z.setUsuarios(usuario.selectAllUsuariosZona(conn, zoid));
				zonas.add(z);
			}
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}

				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}

		return zonas;
	}

}
